package cn.hserver.dns;

import cn.hserver.dns.bean.DnsBean;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class DnsSearch {

    private final static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .callTimeout(120, TimeUnit.SECONDS)
            .pingInterval(5, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            //定义阿里云的dns
            .dns(s -> Arrays.asList(
                    InetAddress.getByAddress(new byte[]{(byte) 223, (byte) 5, (byte) 5, 5}),
                    InetAddress.getByAddress(new byte[]{(byte) 223, (byte) 6, (byte) 6, 6})
            ))
            .build();

    public static List<DnsBean> search(String domian) {
        try {
            final Request request = new Request.Builder()
                    .url("https://dns.alidns.com/resolve?name="+domian)
                    .get().build();
            String string = okHttpClient.newCall(request).execute().body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject!=null&&jsonObject.containsKey("Status")){
                if (jsonObject.getIntValue("Status")==0){
                    JSONArray answer = jsonObject.getJSONArray("Answer");
                    return answer.toList(DnsBean.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws UnknownHostException {
        List<DnsBean> search = search("www.baidu.com");
        System.out.println(search);
    }
}
